package com.genreate.util;

import cn.hutool.core.swing.clipboard.ClipboardUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Entity;
import com.genreate.util.dbUtil.DbUtil;
import com.genreate.util.dbUtil.JdbcConfig;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据库util
 *
 * @author LYS
 * @date 2024-12-16
 */
public class DataBaseUtil {
    public static void main(String[] args) {
        getTableFields(JdbcConfig.mysql_8145_test_xinyuan_manage(),"app_dealer","d");
    }
    /**
     * 获取表字段
     *
     * @param jdbcConfig jdbc配置
     * @param tableName  表名
     * @param prefix     前缀
     * @return 字符串
     */
    public static String getTableFields(JdbcConfig jdbcConfig,String tableName,String prefix) {
        DbUtil.setJdbcConfig(jdbcConfig);
        List<Entity> querys = DbUtil.querys(StrUtil.format("DESC {};", tableName));
        StringBuilder sb = StrUtil.builder("SELECT ");
        for (Entity query : querys) {
            sb.append(StrUtil.format("{}.{},", prefix, query.getStr("Field")));
        }
        if(sb.toString().endsWith(",")){
            sb.deleteCharAt(sb.length()-1);
        }
        sb.append(StrUtil.format(" FROM {} AS {}",tableName,prefix));
        System.out.println(sb);
        ClipboardUtil.setStr(sb.toString());
        return sb.toString();
    }

    /**
     * 获取所有表名
     *
     * @param databaseName
     * @return {@link List }<{@link String }>
     */
    public static List<String> getAllTableNames(String databaseName){
        DbUtil.setJdbcConfig(JdbcConfig.mysql_localhost_emergency());
        String sql = StrUtil.format("SELECT table_name FROM information_schema.tables WHERE table_schema = '{}'", databaseName);
        List<Entity> querys = DbUtil.querys(sql);
        return querys.stream().map(e->e.getStr("TABLE_NAME")).collect(Collectors.toList());
    }
}
